package com.tim.app.ui.activity.selected;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.KeyboardChangeListener;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.Answer;
import com.tim.app.server.entry.Article;
import com.tim.app.server.entry.Comment;
import com.tim.app.server.entry.Dynamic;
import com.tim.app.server.entry.ReplyComment;
import com.tim.app.server.entry.Story;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.CommentDetailResult;
import com.tim.app.server.result.ReplyCommentListResult;
import com.tim.app.server.result.ReplyResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.DynamicDetailActivity;
import com.tim.app.ui.activity.StoryDetailActivity;
import com.tim.app.ui.adapter.comment.ReplyCommentInfoAdapter;
import com.tim.app.ui.view.CommentHeadView;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 评论详情页面
 */
public class CommentDetailActivity extends BaseActivity implements LoadMoreHandler, KeyboardChangeListener.KeyBoardListener {

    public static final String TAG = "CommentDetailActivity";

    private boolean isFromPush = false;

    private ImageButton ibBack;
    private TextView tvTitle;
    private ImageButton ibMore;
    private TextView tvGoto;

    private EmptyLayout emptyLayout;

    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvComment;
    private CommentHeadView headView;
    private ReplyCommentInfoAdapter adapter;
    private List<ReplyComment> dataList;

    private TextView tvPublish;
    private EditText etComment;

    private int pageNumber = 1;
    private KeyboardChangeListener mKeyboardChangeListener;

    private String id;

    private Comment comment;

    public static void start(Context context, String id, boolean isFromPush) {
        Intent intent = new Intent(context, CommentDetailActivity.class);
        intent.putExtra("id", id);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_comment_detail;
    }


    @Override
    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        ibBack = (ImageButton) findViewById(R.id.ibBack);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        ibMore = (ImageButton) findViewById(R.id.ibMore);
        tvGoto = (TextView) findViewById(R.id.tvGoto);

        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvComment = (WrapRecyclerView) findViewById(R.id.wrvComment);
        headView = (CommentHeadView) LayoutInflater.from(this).inflate(R.layout.comment_head_view, null);

        wrvComment.setOverScrollMode(View.OVER_SCROLL_NEVER);
        tvPublish = (TextView) findViewById(R.id.tvPublish);
        etComment = (EditText) findViewById(R.id.etComment);

        emptyLayout = new EmptyLayout(this, load_more);
        emptyLayout.showLoading();
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_message);
        emptyLayout.setEmptyText("还没有回复", "");
        emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.showLoading();
            }
        });

        id = getIntent().getStringExtra("id");
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);

        if (dataList == null) {
            dataList = new ArrayList<>();
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvComment.setLayoutManager(layoutManager);
        adapter = new ReplyCommentInfoAdapter(this, dataList);
        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);
        ibBack.setOnClickListener(this);
        ibMore.setOnClickListener(this);

        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);
        tvPublish.setOnClickListener(this);
        tvGoto.setOnClickListener(this);
        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(etComment.getText().toString())) {
                    tvPublish.setEnabled(true);
                } else {
                    tvPublish.setEnabled(false);
                }
            }
        });
        etComment.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (!UserManager.ins().isLogin()) {//跳转登录并且抢走焦点
                        wrvComment.setFocusable(true);
                        wrvComment.requestFocus();
                        ViewGT.gotoLoginActivity(CommentDetailActivity.this);
                    }
                } else {// 此处为失去焦点时的处理内容

                }
            }
        });

        wrvComment.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                SoftKeyboardUtil.hideSoftKeyboard(etComment);
                return false;
            }
        });
        wrvComment.setAdapter(adapter);
        wrvComment.addHeaderView(headView);
        wrvComment.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(getResources().getColor(R.color.transparent)).size((int) getResources().getDimension(R.dimen.dimen_5)).build());

        EventManager.ins().registListener(EventTag.ON_COMMENT_HEADER_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_REPLY_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_SELECT_PEPLY_COMMENT, eventListener);

    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_COMMENT_HEADER_DELETED://被删除
                    String deleteId = (String) dataobj;
                    if (id.equals(deleteId)) {
                        finish();
                    }
                    break;
                case EventTag.ON_REPLY_DELETED://回复被删除
                    int position = (int) dataobj;
                    dataList.remove(position);
                    adapter.notifyDataSetChanged();
                    break;
                case EventTag.ON_SELECT_PEPLY_COMMENT://选中评论
                    if (null != dataobj) {
                        ReplyComment selectComment = (ReplyComment) dataobj;
                        setInputHint(selectComment.getUserName());
                        isReply = true;
                    } else {
                        setInputHint(comment.getUserMsg().getName());
                        isReply = false;
                    }
                    etComment.setFocusable(true);
                    etComment.requestFocus();
                    SoftKeyboardUtil.showSoftKeyboard(etComment);
                    break;
            }

        }
    };
    boolean isReply = false;

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        if (!isShow) {
            if (isReply) {
                isReply = false;
                adapter.setReplyComment(null);

            }
            etComment.setText("");
            setInputHint("");
        }
    }

    @Override
    public void initData() {
        API_Found.ins().getCommentDetail(TAG, id, detailCallback);
        API_Found.ins().getReplyCommentList(TAG, id, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
    }

    StringResponseCallback detailCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                CommentDetailResult result = new Gson().fromJson(resultValue, CommentDetailResult.class);

                if (null != result && null != result.getRes()) {
                    comment = result.getRes().getComment();
                    showGotoText(comment);
                    setTitle();
                    setInputHint(comment.getUserMsg().getName());
                    headView.setData(comment);
                    emptyLayout.showContent();
                } else {
                    emptyLayout.showEmptyOrError(errCode);
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    /**
     * 回复评论
     *
     * @param content
     */
    public void postReplyComment(String content) {
        if (null == comment)
            return;
        API_Found.ins().addCommentReply(TAG, comment.getId(), comment.getUserMsg().getUserId(), comment.getUserMsg().getName(), content, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    ReplyResult result = new Gson().fromJson(resultValue, ReplyResult.class);
                    if (null != result && null != result.getRes()) {
                        ReplyComment replyComment = result.getRes().getReply();
                        SoftKeyboardUtil.hideSoftKeyboard(etComment);
                        comment.setReplyCount(comment.getReplyCount() + 1);
                        if (null == comment.getReplyList()) {
                            comment.setReplyList(new ArrayList<ReplyComment>());
                        }
                        dataList.add(replyComment);
                        adapter.notifyDataSetChanged();
                    }
                } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                    ToastUtil.showToast("由于对方的设置，你不能回复此评论");
                }
                return false;
            }
        });
    }

    /**
     * 发表回复的 回复
     *
     * @param content
     */
    public void postReplyToReply(String content) {
        ReplyComment replyComment = adapter.getReplyComment();
        if (null == replyComment)
            return;
        API_Found.ins().addCommentReply(TAG, comment.getId(), replyComment.getUserId(), replyComment.getUserName(), content, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    ReplyResult result = new Gson().fromJson(resultValue, ReplyResult.class);
                    if (null != result && null != result.getRes()) {
                        ReplyComment replyComment = result.getRes().getReply();
                        SoftKeyboardUtil.hideSoftKeyboard(etComment);
                        comment.setReplyCount(comment.getReplyCount() + 1);
                        if (null == comment.getReplyList()) {
                            comment.setReplyList(new ArrayList<ReplyComment>());
                        }
                        dataList.add(replyComment);
                        adapter.notifyDataSetChanged();
                    }
                } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                    ToastUtil.showToast("由于对方的设置，你不能回复此评论");
                }
                return false;
            }
        });
    }

    /**
     * 处理跳转
     *
     * @param comment
     */
    private void showGotoText(Comment comment) {
        if (isFromPush) {
            tvGoto.setVisibility(View.VISIBLE);
            if (comment.getType().equals(AppKey.TYPE_ARTICLE)) {
                tvGoto.setText("去文章");
            } else if (comment.getType().equals(AppKey.TYPE_STORY)) {
                tvGoto.setText("去故事");
            } else if (comment.getType().equals(AppKey.TYPE_DYNAMIC)) {
                tvGoto.setText("去动态");
            } else if (comment.getType().equals(AppKey.TYPE_ANSWER)) {
                tvGoto.setText("去回答");
            }
        }
    }


    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                ReplyCommentListResult result = new Gson().fromJson(resultValue, ReplyCommentListResult.class);

                if (null != result && null != result.getRes()) {
                    if (result.getRes().getArraylist() != null) {
                        dataList.clear();
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                ReplyCommentListResult result = new Gson().fromJson(resultValue, ReplyCommentListResult.class);

                if (null != result && null != result.getRes()) {
                    if (result.getRes().getArraylist() != null) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            dataList.addAll(result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                        }
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    /**
     * 更新标题
     */
    private void setTitle() {
        if (null == comment)
            return;
        tvTitle.setText(getString(R.string.replyCount, String.valueOf(comment.getReplyCount())));
    }

    /**
     * 更新输入框的提示语
     *
     * @param hintText
     */
    private void setInputHint(String hintText) {
        if (!TextUtils.isEmpty(hintText)) {
            etComment.setHint(getString(R.string.replySomeone, hintText));
        } else {
            etComment.setHint(getString(R.string.replySomeone, comment.getUserMsg().getName()));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.ON_COMMENT_HEADER_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_REPLY_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_SELECT_PEPLY_COMMENT, eventListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                onBackPressed();
                break;
            case R.id.tvPublish://回复
                String content = etComment.getText().toString().trim();
                if (isReply) {
                    postReplyToReply(content);
                } else {
                    postReplyComment(content);
                }
                break;
            case R.id.tvGoto://跳转详情
                if (comment.getType().equals(AppKey.TYPE_ARTICLE)) {
                    Article article = new Article();
                    article.setId(String.valueOf(comment.getTypeId()));
                    ArticleDetailActivity.start(this, article, false);
                } else if (comment.getType().equals(AppKey.TYPE_STORY)) {
                    Story story = new Story();
                    story.setId(String.valueOf(comment.getTypeId()));
                    ArrayList<Story> list = new ArrayList<>();
                    list.add(story);
                    StoryDetailActivity.start(this, list, 0, false);
                } else if (comment.getType().equals(AppKey.TYPE_DYNAMIC)) {
                    Dynamic dynamic = new Dynamic();
                    dynamic.setId(String.valueOf(comment.getTypeId()));
                    DynamicDetailActivity.start(this, dynamic, false);
                } else if (comment.getType().equals(AppKey.TYPE_ANSWER)) {
                    Answer answer = new Answer();
                    answer.setId(String.valueOf(comment.getTypeId()));
                    AnswerDetailActivity.start(this, answer, false);
                }
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getReplyCommentList(TAG, id, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        SoftKeyboardUtil.hideSoftKeyboard(etComment);
        if (isFromPush) {
            ViewGT.gotoMainActivity(CommentDetailActivity.this);
        } else {
            super.onBackPressed();
        }
    }
}
